package org.javaboy.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkGetNodeDemo implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    static ZooKeeper zk;

    public static void main(String[] args) throws IOException, InterruptedException {
        zk = new ZooKeeper("s2.javaboy.org:2181", 5000, new ZkGetNodeDemo());
        //注意，这个时候其实并没有建立连接
        ZooKeeper.States state = zk.getState();
        System.out.println("state = " + state);
        //暂停，当countDownLatch减为0的时候，程序才会继续执行
        countDownLatch.await();
    }

    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("连接成功");
            try {
                getNode();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            }
            // -1
            countDownLatch.countDown();
        }
    }

    private void getNode() throws InterruptedException, KeeperException {
        List<String> children = zk.getChildren("/", true);
        for (String child : children) {
            byte[] data = zk.getData("/" + child, true, null);
            String s = new String(data);
            System.out.println("s = " + s);
            if (child.equals("javaboy0000000000")) {
                //修改数据
                Stat stat = zk.setData("/" + child, "hello world".getBytes(), -1);
                System.out.println("stat = " + stat);
                byte[] data1 = zk.getData("/" + child, true, null);
                String s1 = new String(data1);
                System.out.println("s1 = " + s1);
                zk.delete("/" + child, -1);
                Stat exists = zk.exists("/" + child, true);
                System.out.println("exists = " + exists);
            }
        }
    }
}
